package com.sihai.ehr.web.action;

import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public abstract class ExportAction extends EHRAction {

    private static final long serialVersionUID = -966758301533552646L;

    public static final String EXPORT_SUCCESS = "export_success";

    public final String getFileName() throws UnsupportedEncodingException {
        return new String(fileName().getBytes(), "iso8859-1");
    }

    protected Map createJxlsTemplateModel(List<?> reports) {
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("reports", reports);
        return map;
    }

    protected InputStream inputStream;


    protected String export(List<?> data) throws Exception {
        try {
            Workbook workbook = new XLSTransformer().transformXLS(getClass().getResourceAsStream("/report/" + getTemplate()), createJxlsTemplateModel(data));
            workbook.setSheetName(0, fileName());
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            workbook.write(out);
            inputStream = new ByteArrayInputStream(out.toByteArray());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return EXPORT_SUCCESS;
    }

    protected abstract String getTemplate();

    public InputStream getInputStream() {
        return inputStream;
    }

    protected abstract String fileName();
}